﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Reflection;
using System.Diagnostics.CodeAnalysis;

namespace GoodStuff
{
    public static class AttributeHelper
    {
        public static T GetAttribute<T>(this object target) where T : Attribute
        {
            return GetAttribute<T>(target.GetType());
        }

        public static T GetAttribute<T>(this ICustomAttributeProvider target) where T : Attribute
        {
            T attribute = (T)target.GetCustomAttributes(typeof(T), true).FirstOrDefault();
            return attribute;
        }

        public static T GetAttribute<T>(this Type target) where T : Attribute
        {
            T attribute = (T)target.GetCustomAttributes(typeof(T), true).FirstOrDefault();
            return attribute;
        }

        public static IEnumerable<T> GetAttributes<T>(this ICustomAttributeProvider target) where T : Attribute
        {
            return target.GetCustomAttributes(typeof(T), true).Cast<T>();
        }
       
        /// <summary>
        /// Returns all properties that have the given attribute applied.
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="target"></param>
        /// <returns></returns>
        public static IEnumerable<PropertyInfo> GetProperties<T>(this object target) where T : Attribute
        {
            Type t = target.GetType();

            return t.GetProperties().Where(p => p.IsDefined(typeof(T), true));
        }

        public static IEnumerable<PropertyInfo> GetProperties<T>(this Type target) where T : Attribute
        {
            return target.GetProperties().Where(p => p.IsDefined(typeof(T), true));
        }

        public static IEnumerable<MethodInfo> GetMethods<T>(this object target) where T : Attribute
        {
            Type t = target.GetType();

            return t.GetMethods().Where(p => p.IsDefined(typeof(T), true));
        }
    }
}
